package com.zunipe.trainticketsystem;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zunipe.trainticketsystem.database.entity.Order;
import com.zunipe.trainticketsystem.database.entity.Train;
import com.zunipe.trainticketsystem.database.entity.User;
import com.zunipe.trainticketsystem.database.handler.OrderHandler;
import com.zunipe.trainticketsystem.database.handler.TrainHandler;
import com.zunipe.trainticketsystem.database.handler.UserHandler;
import com.zunipe.trainticketsystem.databinding.ActivityOrderPaymentBinding;

public class OrderPaymentActivity extends AppCompatActivity {
    ActivityOrderPaymentBinding binding;
    private UserHandler userHandler;
    private TrainHandler trainHandler;
    private OrderHandler orderHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOrderPaymentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);
        userHandler = new UserHandler();
        trainHandler = new TrainHandler();
        orderHandler = new OrderHandler();
        int id = getIntent().getIntExtra("id", 0);
        if (id == 0) {
            finish();
            return;
        }
        Order order = orderHandler.getOrderById(id);
        Train train = trainHandler.getTrainById(order.getTrainId());
        User user = userHandler.getUserById(order.getUserId());
        binding.tvPlaceOfStart.setText(train.getPlaceOfStart());
        binding.tvPlaceOfEnd.setText(train.getPlaceOfEnd());
        binding.tvStartTime.setText(train.getStartTime());
        binding.tvEndTime.setText(train.getEndTime());
        binding.tvTrainNumber.setText(train.getTrainNumber());
        binding.tvOrderNumber.setText(getString(R.string.order_number, order.getOrderNumber()));
        binding.tvUsername.setText(user.getUsername());
        binding.tvType.setText(train.getType());
        binding.tvPaymentStatus.setText(getString(R.string.order_payment_status, order.getStatus()));
        binding.tvPrice.setText(getString(R.string.price, order.getPrice()));

        binding.btnSubmitOrder.setOnClickListener(v -> {
            orderHandler.paymentOrder(order.getId(), "已付款");
            Intent updateOrderPageListBroadcast = new Intent();
            updateOrderPageListBroadcast.setAction("com.zunipe.trainticketsystem.update.order.list");
            updateOrderPageListBroadcast.setPackage("com.zunipe.trainticketsystem");
            sendBroadcast(updateOrderPageListBroadcast);

            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            Toast.makeText(this, "付款成功", Toast.LENGTH_SHORT).show();
        });
    }
}